package com.yami.shop.platform.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.SendUserDropsParam;
import com.yami.shop.bean.param.UserUpdateParam;
import com.yami.shop.common.bean.Minio;
import com.yami.shop.common.bean.Works;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.common.util.pdfUtil.PdfUtils;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.nft.common.model.NftDaw;
import com.yami.shop.nft.common.service.NftDawService;
import com.yami.shop.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Slf4j
@Component
@AllArgsConstructor
public class CopyrightWorksTask {

    @Autowired
    private CopyrightWorksService copyrightWorksService;
    @Autowired
    private NftDawService nftDawService;
    @Autowired
    private ShopConfig shopConfig;
    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private BusinessNftService businessNftService;
    @Autowired
    private UserService userService;

    @XxlJob("copyrightWorksTask")
    public void copyrightWorksTask() throws Exception{
        // 查询待处理数据
        List<CopyrightWorks> copyrightWorksList = copyrightWorksService.list(new QueryWrapper<CopyrightWorks>().eq("status", "2").isNotNull("prod_id").eq("nft_status","1"));

        log.info("产证空投任务开始----------------------");
        for(CopyrightWorks copyrightWorks: copyrightWorksList){
            // 取币校验信息 -- 一个商品只有一个币
            List<NftDaw> nftDaws = nftDawService.selectDawListLimit(copyrightWorks.getDenomId(), 1);
            if(ObjectUtil.isEmpty(nftDaws)){
                continue;
            }
            log.info("产证空投任务开始----------------------businessNft添加数据");

            // businessNft添加数据
            UserUpdateParam param = new UserUpdateParam();
            // 商品信息
            List<SendUserDropsParam> userDropsParams = new ArrayList<>();

            SendUserDropsParam sendUserDropsParam = new SendUserDropsParam();
            sendUserDropsParam.setTargetId(copyrightWorks.getProdId());
            sendUserDropsParam.setType(0);
            sendUserDropsParam.setNums(1);
            userDropsParams.add(sendUserDropsParam);

            param.setDrops(userDropsParams);
            // User
            param.setUserIds(Collections.singletonList(copyrightWorks.getUserId()));
            // 任务空投逻辑
            param.setBusinessType(2);
            // 业务ID
            param.setAirdropBusinessId(copyrightWorks.getWorksId());
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(copyrightWorks.getShopId());
            businessNftService.bindDropById(param, shopDetail);


            log.info("产证空投任务开始----------------------businessNft添加数据--------------------添加数据结束");

            //修改该产证审核信息 ---  1、回填token --- 2、生成产证下载图片
            // 获取PDF 路径 ---- 参数配置读取
            Minio minio = shopConfig.getMinio();
            // 获取 模板
            Works worksConfig = shopConfig.getWorksConfig();
            Map<String,Object> keyWordMap = new HashMap<>();
            keyWordMap.put("worksNo","dtc"+ StrUtil.padPre(String.valueOf(copyrightWorks.getWorksId()),20,"0"));
            keyWordMap.put("worksName",copyrightWorks.getWorksName());
            keyWordMap.put("worksTypeName",getWorksTypeName(copyrightWorks.getWorksType()));
            keyWordMap.put("time",DateUtil.formatDateTime(copyrightWorks.getCreateTime()));
            keyWordMap.put("tokenId",nftDaws.get(0).getDawId());
            // 获取用户实名信息
            User user = userService.getById(copyrightWorks.getUserId());
            keyWordMap.put("name",user.getRealName());
            Map<String,String> imageMap = new HashMap<>();
            imageMap.put("worksImg",minio.getEndpoint() + "/" + minio.getBucketName() + "/" + copyrightWorks.getWorksCoverUrl());
            // 通过PDF模板生成图片
            URL url = new URL(minio.getEndpoint() + "/" + minio.getBucketName() + "/" + worksConfig.getCopyrightWorksTemplate());
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
            PdfUtils.generatePdf(urlConnection.getInputStream(), qrOutputStream, keyWordMap,imageMap,35f);
            //保存图片
            PDDocument document = PDDocument.load(qrOutputStream.toByteArray());
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300); // 使用300dpi解析第一页，可以自行调整dpi大小
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", outputStream);
            MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", outputStream.toByteArray());
            String fileUrl = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.randomUUID() + ".jpg");

            copyrightWorks.setWorksCertificateUrl(fileUrl);
            copyrightWorks.setNftStatus("2");
            copyrightWorks.setTokenId(nftDaws.get(0).getDawId());
            copyrightWorksService.updateById(copyrightWorks);

        }
    }


    private String getWorksTypeName(String worksType){
        //A文字B音乐C 戏剧D 曲艺E 舞蹈F 美术G 摄影H 电影I 视听J 工程设计图、产品设计图 K 地图、示意图L 其他作品 M 口述 N 杂技 O 建筑P 模型
        String worksTypeName = null;
        switch (worksType){
            case "A":worksTypeName = "文字";break;
            case "B":worksTypeName = "音乐";break;
            case "C":worksTypeName = "戏剧";break;
            case "D":worksTypeName = "曲艺";break;
            case "E":worksTypeName = "舞蹈";break;
            case "F":worksTypeName = "美术";break;
            case "G":worksTypeName = "摄影";break;
            case "H":worksTypeName = "电影";break;
            case "I":worksTypeName = "视听";break;
            case "J":worksTypeName = "工程设计图、产品设计图";break;
            case "K":worksTypeName = "地图、示意图";break;
            case "L":worksTypeName = "其他作品";break;
            case "M":worksTypeName = "口述";break;
            case "N":worksTypeName = "杂技";break;
            case "O":worksTypeName = "建筑";break;
            case "P":worksTypeName = "模型";break;
        }
        return worksTypeName;
    }

}
